package com.group11.user.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.group11.common.dto.RegUser;
import com.group11.user.dto.UserInfo;
import com.group11.user.entity.Enterprise;
import com.group11.user.entity.User;
import com.group11.user.entity.UserEnterprise;
import com.group11.user.exception.AccountException;
import com.group11.user.mapper.UserMapper;
import com.group11.user.service.EnterpriseService;
import com.group11.user.service.UserService;
import com.group11.common.vo.UserVO;
import com.group11.user.vo.EnterpriseVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import com.group11.common.pojo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    // Value包不要导错了，导的应该是springboot的包而不是lombok
    @Value("${jwt.secretKey}")
    private String secretKey;
    @Autowired
    private EnterpriseService enterpriseService;

    @PostMapping("reg")
    public ResponseResult<Void> reg(@RequestBody RegUser regUser) {
        try {
            userService.reg(regUser.getAccount(), regUser.getPassword());
        }catch (AccountException e){
            return new ResponseResult<>(202, "Account already exists");
        }
        return new ResponseResult<>(200,"ok");
    }

    @PostMapping("login")
    public ResponseResult<String> login(@RequestBody RegUser regUser, HttpServletResponse response) {
        log.debug("RegUser:{}", regUser);
        //通过调用服务层来获取用户个人信息，并用个人信息生成token
        RegUser result = userService.login(regUser);
        if (result == null) {
            return new ResponseResult<>(201, "账号或密码不正确");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", result.getId());
        map.put("account", result.getAccount());
        map.put("expiry_time",System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
        String jwt= JWTUtil.createToken(map, secretKey.getBytes(StandardCharsets.UTF_8));
        //将生成的和用户相关联的token增加到响应头中
        response.addHeader("Authorization", jwt);
        //接口本身仅返回用户的type类型
        return new ResponseResult<>(result.getType());

    }

    //微服务架构需要一个统一的jwt验证接口，由网关（主要处理不同模块之间相互调用时的跨域问题）发送请求到这个接口
    @PostMapping("verifyJwt")
    public ResponseResult<Void> verifyJwt( String token){
        log.debug("token:{}", token);
        boolean isValid = false;
        try{
            isValid =JWTUtil.verify(token, secretKey.getBytes(StandardCharsets.UTF_8));
        }catch (Exception e){
            e.printStackTrace();
        }
        if (isValid) {
            return ResponseResult.SUCCESS;
        } else {
            return ResponseResult.INVALID_TOKEN;
        }
    }

    @GetMapping("parseJwt")
    //解析jwt，将网关分发的请求中携带的jwt解析为用户信息
    public ResponseResult<UserVO> parseJwt(String token){
        final JWT jwt = JWTUtil.parseToken(token);
        Object id = jwt.getPayload("id");
        UserVO userVO = new UserVO();
        userVO.setId(Integer.parseInt(id.toString()));
        userVO.setAccount(jwt.getPayload("account").toString());
        return new ResponseResult<>(userVO);
    }

    @PostMapping("update")
    public ResponseResult<Void> modifyUser(@RequestHeader int id, @RequestBody UserInfo userInfo) {
        userInfo.setId(id);
        boolean b = userService.updateUser(userInfo);
        if (b) {
            return ResponseResult.SUCCESS;
        }
        return ResponseResult.FAILED;
    }

    @PostMapping("/follow")
    public ResponseResult<Void> follow(@RequestHeader int id, @RequestParam int ent_id) {
        boolean b = userService.followEnterprise(id, ent_id);
        if (!b) {
            return ResponseResult.FAILED;
        }
        return ResponseResult.SUCCESS;
    }

    @PostMapping("/followStatus")
    public ResponseResult<?> getUserEnterPrise(@RequestHeader int id, @RequestParam int ent_id) {
        UserEnterprise userEnterprise = userService.getUserEnterprise(id, ent_id);
        if (userEnterprise == null) {
            return ResponseResult.FAILED;
        }
        return new ResponseResult<>(userEnterprise);
    }

    @GetMapping("/getById")
    public ResponseResult<User> getUserById(@RequestParam int id) {
        return new ResponseResult<>(userService.getById(id));
    }



}
